package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishFlavorService dishFlavorService;
    /**
     * 添加菜品
     * @param category
     * @return
     */
    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加菜品成功");
    }

    /**
     * 菜品分页
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("page")
    public R<Page<Category>> page(Integer page,Integer pageSize){
        //分页构造器
        Page<Category> pageInfo=new Page<>(page, pageSize);
        //lambda条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.orderByDesc(Category :: getCreateTime)
                .orderByAsc(Category::getSort);
        //执行查询条件
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> delete( Long id) {
        categoryService.remove(id);
        return R.success("删除成功");
    }

    /**
     * 根据type字段查询分类列表
     */
    @GetMapping("list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = Wrappers.lambdaQuery(Category.class)
                .eq(category.getType()!=null,Category::getType, category.getType())
                .orderByDesc(Category::getUpdateTime)
                .orderByAsc(Category::getSort);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
